//
//  ScreenshotViewController.swift
//  ZJSwiftKit_Example
//
//  Created by zyx on 2023/2/16.
//  Copyright © 2023 CocoaPods. All rights reserved.
//

import UIKit
import ZJSwiftKit

class ScreenshotViewController: UIViewController {

    var image: UIImage?
    
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if  let _ = image {
            imageView.image = image
        }
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func clickedCircle(_ sender: Any) {
        if  let _ = image {
            imageView.image = image?.zj.circleImage
        }
        
        imageView.zj.blur()
    }
}


extension  UIImage {
    
    /// 视图截图
    public var circleImage: UIImage? {
        
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
        defer {
            UIGraphicsEndImageContext()
        }
        
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        let imageWidth = size.width
        let imageHeight = size.height
        var rect: CGRect
        if imageWidth > imageHeight {
            let x = (imageWidth - imageHeight) * 0.5
            rect = CGRect.init(x: x, y: 0, width: imageHeight, height: imageHeight)
        } else if imageWidth == imageHeight {
            rect = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
        } else {
            let y = (imageHeight - imageWidth) * 0.5
            rect = CGRect.init(x: 0, y: y, width: imageWidth, height: imageWidth)
        }
        context.addEllipse(in: rect)
        context.clip()
        self.draw(in: rect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}
